package com.funky.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.funky.pojo.Number;
import com.funky.dao.NumberMapper;
import com.funky.pojo.User;
import com.funky.service.NumberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funky.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaojin
 * @since 2021-01-08
 */
@Service
public class NumberServiceImpl extends ServiceImpl<NumberMapper, Number> implements NumberService {

  @Autowired
  private NumberMapper numberMapper;

  @Autowired
  private UserService userService;

  @Override
  public Integer addNumber(User user, Integer month) {
    Number number = new Number();

    //会员续费
    if (user.getMember() == 1){
      Number numberTwo = numberMapper.selectById(user.getMemberId());
      numberTwo.setEndTime(DateUtil.offsetDay(numberTwo.getEndTime(), month * 30));
      UpdateWrapper<Number> updateWrapper = new UpdateWrapper();
      int update = numberMapper.update(numberTwo, updateWrapper.eq("id",numberTwo.getId()));
      return update == 1 ? 1:0;
    }else {
      //首充会员
      DateTime date = DateUtil.date();
      String uuid = IdUtil.simpleUUID();
      //用户设置会员卡号
      user.setMemberId(uuid);
      user.setMember(1);
      //会员设置信息
      number.setId(uuid);
      number.setStartTime(date);
      number.setEndTime(DateUtil.offsetDay(date, month * 30));
      UpdateWrapper<User> updateWrapper = new UpdateWrapper();
      boolean update = userService.update(user, updateWrapper.eq("id",user.getId()));
      int insert = numberMapper.insert(number);
      if (update && insert == 1){
        return 1;
      }else {
        return 0;
      }
    }

  }
}
